package com.woniuxy.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.woniuxy.common.Constant;


public class QiNiuUploadUtils {
    public static String uploadFile(byte[] uploadBytes, String filename) {
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = Constant.ACCESSKEY;
        String secretKey = Constant.SECRETKEY;
        String bucket = Constant.BUCKET;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(uploadBytes, filename, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("Uploaded file key: " + putRet.key); // 打印上传的文件名
            return putRet.key; // 返回上传成功的文件名
        } catch (QiniuException ex) {
            System.err.println("Upload failed: " + ex.response.toString());
            return null; // 上传失败返回 null
        }
    }

    public static boolean deleteFile(String fileName) {
        Configuration cfg = new Configuration(Region.region2());
        String accessKey = Constant.ACCESSKEY;
        String secretKey = Constant.SECRETKEY;
        String bucket = Constant.BUCKET;

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            System.out.println("Deleting file key: " + fileName); // 打印删除的文件名
            bucketManager.delete(bucket, fileName);
            System.out.println("Delete success for key: " + fileName);
            return true; // 删除成功
        } catch (QiniuException ex) {
            System.err.println("Delete failed: " + ex.response.toString());
            return false; // 删除失败
        }
    }

    public static void updateFile(byte[] uploadBytes, String filename) {
        String uploadedKey = uploadFile(uploadBytes, filename);
        if (uploadedKey == null) {
            System.err.println("Update failed because upload failed.");
            return;
        }

        boolean isDeleted = deleteFile(uploadedKey);
        if (isDeleted) {
            System.out.println("Old file deleted. Re-uploading...");
            uploadFile(uploadBytes, uploadedKey); // 重新上传使用同一个 key
        } else {
            System.err.println("Update failed because delete failed.");
        }
    }
}